package com.besttone.search;

import com.besttone.app.SuggestionProvider;
import com.besttone.search.R.color;
import com.besttone.search.util.LogUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class MainActivity extends Activity
{
	private GridView grid;
	private DisplayMetrics localDisplayMetrics;
	private View view;
	private Button btn_city_search;
	private Button mSearchBtn;
	private SearchRecentSuggestions suggestions;
	
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		view = this.getLayoutInflater().inflate(R.layout.main, null);
		setContentView(view);
		
		btn_city_search = (Button) findViewById(R.id.btn_city);
		btn_city_search.setOnClickListener(searchCityListner);
		
	    mSearchBtn = ((Button)findViewById(R.id.start_search));
	    mSearchBtn.setOnClickListener(searchHistroyListner);

		localDisplayMetrics = getResources().getDisplayMetrics();
		
		suggestions = new SearchRecentSuggestions(this,
				SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
		
		grid = (GridView)view.findViewById(R.id.my_grid);
		ListAdapter adapter = new GridAdapter(this);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(mOnClickListener);
	}
    
    private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() {
    	public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SearchActivity.class);
			startActivity(intent);
    	}
    };
    
    private Button.OnClickListener searchCityListner = new Button.OnClickListener() {
    	public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SelectCityActivity.class);
			intent.putExtra("SelectCityName", btn_city_search.getText().toString());
			startActivityForResult(intent, 100);
		}
    };
    
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode);
		String str = null;
		String cityName = (String) this.btn_city_search.getText();
		if (resultCode == RESULT_OK) {
			str = data.getStringExtra("cityName");
			LogUtils.d(LogUtils.LOG_TAG, "new city:" + str);
			LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName);
			super.onActivityResult(requestCode, resultCode, data);
			this.btn_city_search.setText(str);
		}
	}
	
	private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
			TextView text = (TextView)v.findViewById(R.id.activity_name);
			String keyword = text.getText().toString();
			Intent intent = new Intent();
			if (keyword != null) {
				if ("更多".equals(keyword)) {
					intent.setClass(MainActivity.this, MoreKeywordActivity.class);
					startActivity(intent);
				} else {
					intent.setClass(MainActivity.this, SearchResultActivity.class);
					Bundle bundle = new Bundle();
		    		bundle.putString("keyword", keyword);
		    		intent.putExtras(bundle);
		    		
		    		suggestions.saveRecentQuery(keyword, null);
		    		
		    		startActivity(intent);
				}
			}
		}
	};
	
	public class GridAdapter extends BaseAdapter 
	{
		private LayoutInflater inflater;
		
		public GridAdapter(Context context) 
		{
			inflater = LayoutInflater.from(context);
		}

		public final int getCount() 
		{
			return 6;
		}

		public final Object getItem(int paramInt) 
		{
			return null;
		}

		public final long getItemId(int paramInt) 
		{
			return paramInt;
		}

		public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) 
		{
			paramView = inflater.inflate(R.layout.activity_label_item, null);
			TextView text = (TextView)paramView.findViewById(R.id.activity_name);
			text.setTextSize(15);
			text.setTextColor(color.text_color_grey);
			
			switch(paramInt)
			{
				case 0:
				{
					text.setText("KTV");
					Drawable draw = getResources().getDrawable(R.drawable.ktv);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 1:
				{
					text.setText("宾馆");	
					Drawable draw = getResources().getDrawable(R.drawable.hotel);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 2:
				{
					text.setText("加油站");	
					Drawable draw = getResources().getDrawable(R.drawable.gas);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 3:
				{
					text.setText("川菜");	
					Drawable draw = getResources().getDrawable(R.drawable.chuan);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 4:
				{
					text.setText("快递");	
					Drawable draw = getResources().getDrawable(R.drawable.kuaidi);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 5:
				{
					text.setText("更多");	
					Drawable draw = getResources().getDrawable(R.drawable.more);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
//				case 6:
//				{
//					text.setText("最近浏览");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_history);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				
//				case 7:
//				{
//					text.setText("个人中心");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				case 8:
//				{
//					text.setText("更多");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_more);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
			}

			paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density));
			paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3));
			
			return paramView;
		}
	}
	
    protected static final int MENU_ABOUT = Menu.FIRST;
    protected static final int MENU_Quit = Menu.FIRST+1;
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, " 关于 ...");
		menu.add(0, MENU_Quit, 0, " 结束 ");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ABOUT:
			openOptionsDialog();
			break;
		case MENU_Quit:
			showExitAlert();
			break;
		}
		return true;
		}
	
	private void openOptionsDialog() { 
		new AlertDialog.Builder(MainActivity.this)
		.setTitle(R.string.about_title)
		.setMessage(R.string.about_msg)
		.setPositiveButton(R.string.confirm,
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {}
				})
		.setNegativeButton(R.string.homepage_label,
				new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialoginterface, int i){
							//go to url
							Uri uri = Uri.parse(getString(R.string.homepage_uri));
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							startActivity(intent);
						}
				})
		   .show();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK ){
			showExitAlert();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private void showExitAlert() {
        new AlertDialog.Builder(this)
        .setTitle(R.string.prompt)
        .setMessage(R.string.quit_desc)
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {}
                })
        .setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    	exitApp();
                    }
                }).show();
	}
	
	//彻底关闭程序
	protected void exitApp() {
	    super.onDestroy();
	    Client.release();
	    System.exit(0);
	    // 或者下面这种方式
	    // android.os.Process.killProcess(android.os.Process.myPid());
	}

}
